<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 请求返回成功信息
 * @param array $data
 * @return \think\response\Json
 */
function success($data = []){
    return json(['code'=>0, 'msg'=>'success', 'data'=>$data]);
}

/**
 * 请求返回错误信息
 * @param $code
 * @param $msg
 * @param $status
 * @return \think\response\Json
 */
function error($code, $msg, $status){
    return json(['code'=>$code, 'msg'=>$msg, 'data'=>[]], $status);
}

/**
 *
 * 获取客户端真实ip
 * @return int
 */
function getIp(){
    $realip = '';
    $unknown = 'unknown';
    if (isset($_SERVER)){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach($arr as $ip){
                $ip = trim($ip);
                if ($ip != 'unknown'){
                    $realip = $ip;
                    break;
                }
            }
        }else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){
            $realip = $_SERVER['REMOTE_ADDR'];
        }else{
            $realip = $unknown;
        }
    }else{
        if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        }else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){
            $realip = getenv("HTTP_CLIENT_IP");
        }else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){
            $realip = getenv("REMOTE_ADDR");
        }else{
            $realip = $unknown;
        }
    }
    $realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;
    return $realip;
}

/**
 * ip2long
 * @return int
 */
function getIpLong(){
    return intval(sprintf("%u", ip2long(getIp())));
}

function set_session($key, $value, $life){
    if (!isset($_SESSION)) {
        session_start();  // 开启session，使用原生session必须手动开启
    }
    ini_set('session.gc_maxlifetime', $life);   // 设置session生命周期
    ini_set('session.cookie_lifetime', $life);  // 设置cookie生命周期，0表示客户端浏览器关闭则cookie失效
    //ini_set('session.gc_probability', 1);       // gc回收机制的概率，默认1
    //ini_set('session.gc_divisor', 100);         // gc回收机制的概率，默认100
    $_SESSION['session.start_time'] = time();   // 设置session修改的时间
    $_SESSION[$key] = $value;
}

/**
 * 递归下级
 * @param array $list
 * @param int $pid
 * @param int $deep
 * @return array
 */
function infinite($list = [], $pid = 0, $deep = 0){
    static $arr = [];
    foreach ($list as $v){
        if($v['pid'] == $pid){
            $v['deep'] = $deep;
            $arr[] = $v;
            infinite($list,$v['id'],$deep + 1);
        }
    }
    return $arr;
}

/**
 * 递归查询顶级id
 * @param array $list
 * @param $pid
 * @return int
 */
function infiniteTop($list = [], $pid){
    static $id = 0;
    foreach ($list as $v){
        if($v['id'] == $pid && $v['pid'] != 0){
            infiniteTop($list, $v['pid']);
        } else {
            $id = $v['id'];
        }
    }
    return $id;
}

/**
 * 记录后台操作日志
 * @param $logs
 * @return bool
 */
function logs($logs){
    if (empty($logs)) return true;
    $data = [];
    foreach ($logs as $k=>$v) {
        $log['title'] = $v[0];
        $log['type']  = $v[1];
        $log['desc']  = $v[2];
        $log['uid']   = \think\Session::get('login');
        $log['uip']   = getIpLong();
        $log['create_time'] = time();
        $data[] = $log;
    }
    db('admin_log')->insertAll($data);
}

/**
 * 比对两个数组，并记录相同键不同值的变化，用于记录日志修改变化
 * @param $params array  要修改的值
 * @param $info   array  原值
 * @return string
 */
function compare($params,$info){
    $str = '';
    foreach($params as $k=>$v){
        foreach($info as $k1=>$v1){
            if($k == $k1 && $v != $v1){
                $str .= "，“{$k1}”：{$v1} -> {$v}";
            }
        }
    }
    return $str;
}

/**
 * 获取数据库配置
 * @return array
 */
function get_config(){
    // 获取配置文件信息
    $list = db('config')->select();
    $config = [];
    if(!empty($list)){
        foreach($list as $v){
            $config[$v['key']] = $v['value'];
        }
    }
    return $config;
}

/**
 * 搜索调用
 * @param array $search 查询条件
 * @param array $name 名称 精确查询
 * @param array $time 时间 范围查询
 * @param array $status 状态 精确查存
 * @return array
 * */
function search($search,$name=[],$time=[],$status=[]){
    $where = '';
    $params = array();
    if(empty($search)){  //没有查询条件返回空数组
        return array('where'=>$where,'params'=>$params);
    }
    if(!empty($name) && !empty($search['search_name'])){  //输入精确查找
        $search['search_name'] = str_filter($search['search_name']);
        foreach($name as $k=>$v){
            $search_name = strtolower($search['search_name']);
            $where .= $k == 0 ? "({$v} like '%{$search_name}%'" : " or {$v} like '%{$search_name}%'";
        }
        $where .= ')';
        $params['search_name'] = $search['search_name'];
    }
    if(!empty($time)){  //时间范围查找
        foreach($time as $k=>$v){
            $k = $k ?: '';
            $start_time = isset($search['start_time'.$k]) ? strtotime(date('Y-m-d 00:00:00',strtotime($search['start_time'.$k]))) : 0;
            $end_time   = isset($search['end_time'.$k]) ? strtotime(date('Y-m-d 23:59:59',strtotime($search['end_time'.$k]))) : 0;
            $and = $where ? ' and ' : '';
            if (isset($search['start_time'.$k]) && !isset($search['end_time'.$k])) {
                $where .= "{$and}{$v} >= {$start_time}";
                $params['start_time'.$k] = $search['start_time'.$k];
            } elseif (!isset($search['start_time'.$k]) && isset($search['end_time'.$k])) {
                $where .= "{$and}{$v} <= {$end_time}";
                $params['end_time'.$k] = $search['end_time'.$k];
            } elseif (isset($search['start_time'.$k]) && isset($search['end_time'.$k])) {
                $where .= "{$and}{$v} between {$start_time} and {$end_time}";
                $params['start_time'.$k] = $search['start_time'.$k];
                $params['end_time'.$k] = $search['end_time'.$k];
            }
        }
    }
    if(!empty($status) && !empty($search)){  //选择精确查找
        foreach($status as $k=>$v){
            $val = explode('.',$v);
            $val = strpos($v,'.') ? $val[1] : $v;
            $and = $where ? ' and ' : '';
            if(in_array($val,array_keys($search))){
                $where .= "{$and}{$v} = '{$search[$val]}'";
                $params[$val] = $search[$val];
            }
        }
    }
    return array('where'=>$where,'params'=>$params);
}

/**
 * 排序
 * @param $params
 * @return array
 */
function sort_list($params){
    if (empty($params['sort_filed']) || empty($params['sort_order'])) {
        return array();
    }
    if ($params['sort_order'] == 'descending') {
        $order = 'desc';
    } else {
        $order = 'asc';
    }
    return array($params['sort_filed']=>$order);
}

/**
 * 文件上传
 * @param $files object 文件流
 * @param $fileName string 文件目录名
 * @return array
 * @throws Exception
 */
function upload($files, $fileName){
    $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . $fileName;  //上传目录
    foreach ( $files as $file ) {
        // 移动到框架应用/public/uploads/目录下
        $info = $file->validate(['size'=>2097152,'ext'=>'jpg,png,gif'])->rule('uniqid')->move($path);
        if( false === $info ) throw new \Exception($file->getError(), -1);   // 上传失败获取错误信息

        //$thumb = \think\Image::open($info->getPathName());
        // 按照原图的比例生成一个最大为250*250的缩略图,居中剪裁并保存
        //$thumb->thumb(250, 250,\think\Image::THUMB_CENTER)->save($path. DS .'s'.$info->getSaveName());
        // 成功上传后 获取上传信息
        $file_path[] = 'http://'.$_SERVER['HTTP_HOST']. DS . 'uploads'. DS . $fileName . DS .$info->getSaveName();
    }
    return $file_path;
}

function str_filter($str) {
    $str = trim($str);
    $str = stripslashes($str);
    return $str;
}